# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify, make_response
import os
from werkzeug.utils import secure_filename
import pandas as pd
from process import file_process

app = Flask(__name__)


def allow_cors(func):
    def wrapper(*args, **kwargs):
        response = make_response(func(*args, **kwargs))
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response
    return wrapper


# 允许上传的文件格式
ALLOWED_EXTENSIONS = {'xls', 'xlsx'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['POST'])
@allow_cors
def upload_file():
    # 检查是否有文件在请求中
    if 'file' not in request.files:
        return jsonify({'error': 'No file part in the request'}), 400

    file = request.files['file']

    # 如果用户没有选择文件，浏览器也会提交一个空的文件名
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join('D:/pojects/PyCharmPojects/uploads', filename)  # 设置文件保存路径
        file.save(filepath)

        try:
            # 尝试读取文件
            # if filename.endswith('.xls'):
            #     df_tmp = pd.read_excel(filepath)
            #     report_date = df_tmp.iloc[1, 0].split(' ')[1]
            #     df = pd.read_excel(filepath, sheet_name=0, skiprows=3)
            # else:
            #     df_tmp = pd.read_excel(filepath)
            #     report_date = df_tmp.iloc[1, 0].split(' ')[1]
            #     df = pd.read_excel(filepath, skiprows=3)
            df = pd.read_excel(filepath, skiprows=3)
            report_date =df['计划发布时间'][0]

            # 检查必要的字段是否存在，这里以'Column1'和'Column2'为例
            required_columns = {'系统', '需求编号'}
            if not required_columns.issubset(df.columns):
                return jsonify({'error': 'Missing required columns'}), 400

            # 文件处理逻辑...
            file_process(df, report_date)
            # 如果处理成功
            return jsonify({'message': 'success'}), 200

        except Exception as e:
            # 如果处理失败，返回错误信息
            return jsonify({'error': str(e)}), 500

    else:
        return jsonify({'error': 'File format is not allowed'}), 400


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8088, debug=True)






